<template>
  <div class="learning-progress-page">
    <!-- 顶部导航 -->
    <van-nav-bar
      title="我的学习进度"
      left-arrow
      @click-left="$router.back()"
      class="nav-bar"
    />

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <van-loading size="24px" vertical>加载中...</van-loading>
    </div>

    <!-- 主要内容 -->
    <div v-else class="content">
      <!-- 学习概览卡片 -->
      <div class="overview-section">
        <h3 class="section-title">学习概览</h3>
        <div class="overview-cards">
          <div class="overview-card">
            <div class="card-icon">📚</div>
            <div class="card-content">
              <div class="card-value">{{ overview?.totalCourses || 0 }}</div>
              <div class="card-label">总课程</div>
            </div>
          </div>
          
          <div class="overview-card">
            <div class="card-icon">✅</div>
            <div class="card-content">
              <div class="card-value">{{ overview?.completedCourses || 0 }}</div>
              <div class="card-label">已完成</div>
            </div>
          </div>
          
          <div class="overview-card">
            <div class="card-icon">⏱️</div>
            <div class="card-content">
              <div class="card-value">{{ overview?.studyTimeFormatted || '0分钟' }}</div>
              <div class="card-label">学习时长</div>
            </div>
          </div>
          
          <div class="overview-card">
            <div class="card-icon">📈</div>
            <div class="card-content">
              <div class="card-value">{{ overview?.courseCompletionRate || '0' }}%</div>
              <div class="card-label">完成率</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 学习进度详情 -->
      <div class="progress-section">
        <h3 class="section-title">学习进度</h3>
        
        <!-- 总体进度 -->
        <div class="progress-card">
          <div class="progress-header">
            <span class="progress-title">总体进度</span>
            <span class="progress-value">{{ stats?.overview?.averageCourseProgress || '0' }}%</span>
          </div>
          <van-progress 
            :percentage="Number(stats?.overview?.averageCourseProgress || 0)"
            color="#1989fa"
            track-color="#f2f3f5"
            :show-pivot="false"
          />
          <div class="progress-details">
            <span>已完成 {{ stats?.overview?.completedLessons || 0 }} / {{ stats?.overview?.totalLessons || 0 }} 课时</span>
          </div>
        </div>

        <!-- 课程进度列表 -->
        <div class="course-progress-list">
          <div 
            v-for="course in stats?.courseDetails || []" 
            :key="course.courseId"
            class="course-progress-item"
            @click="goToCourse(course)"
          >
            <div class="course-info">
              <h4 class="course-title">{{ course.courseTitle }}</h4>
              <div class="course-meta">
                <span class="lesson-count">{{ course.currentLesson }}/{{ course.totalLessons }} 课时</span>
                <span class="study-time">{{ formatStudyTime(course.studyTime) }}</span>
              </div>
            </div>
            <div class="course-progress">
              <div class="progress-circle">
                <van-circle
                  v-model:current-rate="course.progress"
                  :rate="course.progress"
                  :speed="100"
                  :size="50"
                  :stroke-width="4"
                  color="#1989fa"
                  layer-color="#f2f3f5"
                  :text="Math.round(course.progress) + '%'"
                />
              </div>
              <van-icon name="arrow" class="arrow-icon" />
            </div>
          </div>
        </div>
      </div>

      <!-- 最近学习 -->
      <div class="recent-section">
        <h3 class="section-title">最近学习</h3>
        <div class="recent-list">
          <div 
            v-for="lesson in stats?.recentActivity?.recentLessons || []"
            :key="lesson.lessonId"
            class="recent-item"
            @click="goToLesson(lesson)"
          >
            <div class="recent-icon">
              <van-icon name="play-circle" size="20" color="#1989fa" />
            </div>
            <div class="recent-content">
              <h4 class="recent-title">{{ lesson.lessonTitle }}</h4>
              <div class="recent-meta">
                <span class="recent-time">{{ formatTime(lesson.lastWatchAt) }}</span>
                <span class="recent-progress">进度: {{ lesson.progress }}%</span>
              </div>
            </div>
            <div class="recent-status">
              <van-tag v-if="lesson.progress === 100" type="success" size="small">已完成</van-tag>
              <van-tag v-else type="primary" size="small">学习中</van-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 学习统计 -->
      <div class="stats-section">
        <h3 class="section-title">学习统计</h3>
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-label">平均每课程学习时长</div>
            <div class="stat-value">{{ formatStudyTime(stats?.timeStats?.averageStudyTimePerCourse || 0) }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">平均每课时观看时长</div>
            <div class="stat-value">{{ formatStudyTime(stats?.timeStats?.averageWatchTimePerLesson || 0) }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">学习效率</div>
            <div class="stat-value">{{ stats?.efficiencyStats?.averageProgressPerHour || '0' }}%/小时</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">最后学习时间</div>
            <div class="stat-value">{{ formatTime(stats?.recentActivity?.lastActivityDate) }}</div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <van-empty
        v-if="!loading && (!stats || !stats.overview || stats.overview.totalCourses === 0)"
        image="search"
        description="还没有学习记录"
        class="empty-state"
      >
        <van-button type="primary" size="small" @click="goToStudyCenter">
          开始学习
        </van-button>
      </van-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { StudyService } from '@/api/services';
import { showToast } from 'vant';

const router = useRouter();

// 响应式数据
const loading = ref(true);
const overview = ref<any>(null);
const stats = ref<any>(null);

// 获取学习概览数据
const fetchOverview = async () => {
  try {
    const result = await StudyService.getProgressOverview();
    if (result && result.code === 200) {
      overview.value = result.data;
    }
  } catch (error) {
    console.error('获取学习概览失败:', error);
  }
};

// 获取详细统计数据
const fetchStats = async () => {
  try {
    const result = await StudyService.getLearningStats({ period: 'all' });
    if (result && result.code === 200) {
      stats.value = result.data;
    }
  } catch (error) {
    console.error('获取学习统计失败:', error);
  }
};

// 初始化数据
const initData = async () => {
  loading.value = true;
  try {
    await Promise.all([
      fetchOverview(),
      fetchStats()
    ]);
  } catch (error) {
    showToast('加载数据失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 格式化学习时长
const formatStudyTime = (seconds: number): string => {
  if (!seconds || seconds === 0) return '0分钟';
  
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`;
  }
  return `${minutes}分钟`;
};

// 格式化时间
const formatTime = (dateString: string): string => {
  if (!dateString) return '暂无';
  
  const date = new Date(dateString);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (days === 0) {
    return '今天';
  } else if (days === 1) {
    return '昨天';
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return date.toLocaleDateString();
  }
};

// 跳转到课程详情
const goToCourse = (course: any) => {
  router.push(`/study/course/${course.courseId}`);
};

// 跳转到课时
const goToLesson = (lesson: any) => {
  router.push(`/video/${lesson.lessonId}?courseId=${lesson.courseId}&title=${encodeURIComponent(lesson.lessonTitle)}`);
};

// 跳转到学习中心
const goToStudyCenter = () => {
  router.push('/study');
};

// 页面初始化
onMounted(() => {
  initData();
});
</script>

<script lang="ts">
export default {
  name: 'LearningProgressPage'
};
</script>

<style scoped>
.learning-progress-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.nav-bar {
  background: #fff;
  border-bottom: 1px solid #ebedf0;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50vh;
}

.content {
  padding: 4.26667vw;
}

.section-title {
  font-size: 4.8vw;
  font-weight: 600;
  color: #323233;
  margin: 0 0 3.2vw 0;
}

/* 概览卡片 */
.overview-section {
  margin-bottom: 6.4vw;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 3.2vw;
}

.overview-card {
  background: #fff;
  border-radius: 2.13333vw;
  padding: 4.26667vw;
  display: flex;
  align-items: center;
  gap: 2.66667vw;
  box-shadow: 0 0.53333vw 2.13333vw rgba(0, 0, 0, 0.05);
}

.card-icon {
  font-size: 6.4vw;
  line-height: 1;
}

.card-content {
  flex: 1;
}

.card-value {
  font-size: 4.8vw;
  font-weight: 600;
  color: #323233;
  line-height: 1.2;
}

.card-label {
  font-size: 3.2vw;
  color: #969799;
  margin-top: 0.53333vw;
}

/* 进度部分 */
.progress-section {
  margin-bottom: 6.4vw;
}

.progress-card {
  background: #fff;
  border-radius: 2.13333vw;
  padding: 4.26667vw;
  margin-bottom: 3.2vw;
  box-shadow: 0 0.53333vw 2.13333vw rgba(0, 0, 0, 0.05);
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2.66667vw;
}

.progress-title {
  font-size: 4.26667vw;
  font-weight: 500;
  color: #323233;
}

.progress-value {
  font-size: 4.26667vw;
  font-weight: 600;
  color: #1989fa;
}

.progress-details {
  margin-top: 2.66667vw;
  font-size: 3.46667vw;
  color: #969799;
}

/* 课程进度列表 */
.course-progress-list {
  background: #fff;
  border-radius: 2.13333vw;
  overflow: hidden;
  box-shadow: 0 0.53333vw 2.13333vw rgba(0, 0, 0, 0.05);
}

.course-progress-item {
  display: flex;
  align-items: center;
  padding: 4.26667vw;
  border-bottom: 1px solid #f2f3f5;
  cursor: pointer;
  transition: background-color 0.2s;
}

.course-progress-item:last-child {
  border-bottom: none;
}

.course-progress-item:active {
  background: #f2f3f5;
}

.course-info {
  flex: 1;
  min-width: 0;
}

.course-title {
  font-size: 4.26667vw;
  font-weight: 500;
  color: #323233;
  margin: 0 0 1.06667vw 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.course-meta {
  display: flex;
  gap: 2.66667vw;
  font-size: 3.2vw;
  color: #969799;
}

.course-progress {
  display: flex;
  align-items: center;
  gap: 2.66667vw;
}

.arrow-icon {
  color: #c8c9cc;
  font-size: 4.26667vw;
}

/* 最近学习 */
.recent-section {
  margin-bottom: 6.4vw;
}

.recent-list {
  background: #fff;
  border-radius: 2.13333vw;
  overflow: hidden;
  box-shadow: 0 0.53333vw 2.13333vw rgba(0, 0, 0, 0.05);
}

.recent-item {
  display: flex;
  align-items: center;
  padding: 4.26667vw;
  border-bottom: 1px solid #f2f3f5;
  cursor: pointer;
  transition: background-color 0.2s;
}

.recent-item:last-child {
  border-bottom: none;
}

.recent-item:active {
  background: #f2f3f5;
}

.recent-icon {
  margin-right: 3.2vw;
}

.recent-content {
  flex: 1;
  min-width: 0;
}

.recent-title {
  font-size: 4.26667vw;
  font-weight: 500;
  color: #323233;
  margin: 0 0 1.06667vw 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.recent-meta {
  display: flex;
  gap: 2.66667vw;
  font-size: 3.2vw;
  color: #969799;
}

.recent-status {
  margin-left: 2.66667vw;
}

/* 学习统计 */
.stats-section {
  margin-bottom: 6.4vw;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 3.2vw;
}

.stat-item {
  background: #fff;
  border-radius: 2.13333vw;
  padding: 4.26667vw;
  text-align: center;
  box-shadow: 0 0.53333vw 2.13333vw rgba(0, 0, 0, 0.05);
}

.stat-label {
  font-size: 3.2vw;
  color: #969799;
  margin-bottom: 1.6vw;
}

.stat-value {
  font-size: 4.26667vw;
  font-weight: 600;
  color: #323233;
}

/* 空状态 */
.empty-state {
  margin-top: 10.66667vw;
  padding: 8vw 4vw;
}

/* 响应式调整 */
@media (max-width: 375px) {
  .overview-cards {
    grid-template-columns: 1fr;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
